package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransAppPayRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayFundTransAppPayResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.AlipayService;
import com.ruoyi.common.enums.ResultCodeEnum;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j

@Service("aliPayService")
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    public ISysConfigService sysConfigService;

    @Override
    public ResponseData createOrder(String orderNo, String totalAmount, String body)  {
        return null;
    }

    @Override
    public ResponseData createPrecreateOrder(String appId, String privateKey, String publicKey, String orderNo, String totalAmount, String subject , String body)  {

        String payGateway =sysConfigService.selectConfigByKey("sys.bussine.payGateway");
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId, privateKey, "json", "UTF-8", publicKey, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.precreate
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        request.setBizContent(bizContent.toString());
        request.setNotifyUrl(payGateway+"/pay/alipay/notifySucc");

        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info(String.format("发起支付宝支付请求接口成功！返回内容：%s",response.getBody()));
                return new SuccessResponseData(response.getQrCode());
            }
            log.info(String.format("发起支付宝支付请求失败！返回内容：%s", JSON.toJSONString(response)));

            return new ErrorResponseData(
                    ResultCodeEnum.ALIPAY_SERVER_ERROR.getMessage()+":"+response.getSubMsg());

        } catch (AlipayApiException e) {
            log.error("",e);
            return new ErrorResponseData(ResultCodeEnum.ALIPAY_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public String createFundTransUniTransfer(String appId, String privateKey, String publicKey, String orderNo, String totalAmount, String subject, String body) throws  AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId,privateKey,"json","UTF-8",publicKey,"RSA2");
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\""+orderNo+"\"," +
                "\"trans_amount\":"+totalAmount+"," +
                "\"product_code\":\"STD_RED_PACKET\"," +
                "\"biz_scene\":\"PERSONAL_COLLECTION\"," +
                "\"order_title\":\""+subject+"\"," +
                "\"original_order_id\":\"20190620110075000006640000063056\"," +
                "\"payee_info\":{" +
                "\"identity\":\"208812*****41234\"," +
                "\"identity_type\":\"ALIPAY_USER_ID\"," +
                "\"name\":\"黄龙国际有限公司\"" +
                "    }," +
                "\"remark\":\"飞聊红包领取\"," +
                "\"business_params\":\"{\\\"sub_biz_scene\\\":\\\"REDPACKET\\\"}\"" +
                "  }");
        AlipayFundTransUniTransferResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public ResponseData createFundTransAppPay(String appId, String privateKey, String publicKey, String orderNo, String totalAmount, String subject, String body) throws  AlipayApiException {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        certAlipayRequest.setAppId(appId);
        certAlipayRequest.setPrivateKey(privateKey);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("UTF-8");
        certAlipayRequest.setSignType("RSA2");
        /*certAlipayRequest.setCertPath(app_cert_path);
        certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
        certAlipayRequest.setRootCertPath(alipay_root_cert_path);*/
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

        AlipayFundTransAppPayRequest request = new AlipayFundTransAppPayRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\""+orderNo+"\"," +
                "\"trans_amount\":"+totalAmount+"," +
                "\"product_code\":\"STD_RED_PACKET\"," +
                "\"biz_scene\":\"PERSONAL_PAY\"," +
                "\"remark\":\"拼手气红包\"," +
                "\"order_title\":\"拼手气红包\"" +
                //"\"business_params\":\"{\\\"sub_biz_scene\\\":\\\"REDPACKET\\\",\\\"payer_binded_alipay_uid:\\\"2088302510459335\\\"}\"" +
                "  }");

        try {
            AlipayFundTransAppPayResponse response = alipayClient.pageExecute(request);

            if(response.isSuccess()){
                log.info(String.format("发起支付宝支付请求接口成功！返回内容：%s",response.getBody()));
                return new SuccessResponseData( response.getOrderId());
            }
            log.info(String.format("发起支付宝支付请求失败！返回错误码：%s",response.getCode()));

            return new ErrorResponseData(
                    ResultCodeEnum.ALIPAY_SERVER_ERROR.getMessage()+":"+response.getSubMsg());


        } catch (AlipayApiException e) {
            log.error("",e);
            return new ErrorResponseData(ResultCodeEnum.ALIPAY_SERVER_ERROR.getMessage());
        }

    }

    @Override
    public String createWapPayOrder(String orderNo, String totalAmount, String body)  {
        return null;
    }

    @Override
    public boolean checkPayResult(String alipayPublicKey,Map<String, String> params)  {
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
        } catch (AlipayApiException e) {
            log.error("",e);
        }
        return flag;
    }

    @Override
    public boolean checkAppId(String app_id,String appId) {
        log.debug(String.format("local config appId is:%s,param app_id is:%s",appId,app_id));
        if(appId.equals(app_id)){
            return true;
        }
        return false;
    }

    @Override
    public boolean checkSellerEmail(String seller_email) {
        return false;
    }
}
